package cn.getway.filter;

import cn.getway.config.web.RequestPathConfig;
import cn.getway.config.web.ResponseMessage;
import cn.getway.config.web.ResponseStatusCode;
import cn.getway.utils.GsonTool;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import static com.netflix.zuul.context.RequestContext.getCurrentContext;

/**
 * 服务的认证
 *
 * @Author: 毛苏宇
 * User: me
 * Date: 2020/6/22
 * Time: 0:24
 * Description:
 */
@Component
public class ServiceFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        //请求地址
        final String requestURI = getCurrentContext().getRequest().getRequestURI();
        for (String ig : RequestPathConfig.getIgnoreUrls()) {
            if (requestURI.contains(ig)) {
                System.out.println("拒绝请求地址：" + requestURI);
                return false;
            }
        }
        System.out.println("服务请求地址："+requestURI);
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取该请求的上下文
        RequestContext context = getCurrentContext();
        context.getResponse().setContentType("text/html;charset=UTF-8");
        //得到请求
        HttpServletRequest request = context.getRequest();
        Cookie[] cookies = request.getCookies();
        String jwtToken = null;
        //从cookies中得到token
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if ("auth".equals(cookie.getName())) {
                    jwtToken = cookie.getValue();
                    break;
                }
            }
        }
        //token是否为空
        if (jwtToken == null || jwtToken.length() <= 0) {
            context.setSendZuulResponse(false);
            context.setResponseBody(GsonTool.objectToJson(new ResponseMessage(ResponseStatusCode.CODE_NO_LOGIN,"尚未登录，请登录",null)));
            return null;
        }
        try {
            //使用Jwt解析器检查签名是否有效
            Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(jwtToken).getBody();
            //将claim添加到请求中，方便其它服务获取到用户id
            Map<String, List<String>> requestQueryParams = context.getRequestQueryParams();
            if (requestQueryParams == null) {
                requestQueryParams = new HashMap<>();
            }
            requestQueryParams.put("jwtId", Arrays.asList(claims.get("jwtId").toString()));
            requestQueryParams.put("jwtIdentity", Arrays.asList(claims.get("jwtIdentity").toString()));
            requestQueryParams.put("jwtUsername", Arrays.asList(claims.get("jwtUsername").toString()));
            context.setRequestQueryParams(requestQueryParams);
            return null;
        } catch (SignatureException e) {
            System.out.println(e.getMessage());
            context.setSendZuulResponse(false);
            context.setResponseBody(GsonTool.objectToJson(new ResponseMessage(ResponseStatusCode.CODE_INVALID_TOKEN,"登录状态失效，请重新登录",null)));
            return null;
        } catch (Exception e){
            System.out.println(e.getMessage());
            context.setSendZuulResponse(false);
            context.setResponseBody(GsonTool.objectToJson(new ResponseMessage(ResponseStatusCode.CODE_SYSTEM_ERROR,"用户信息校验错误",null)));
            return null;
        }
    }
}